package com.cqupt.utils;

import cn.hutool.core.util.StrUtil;
import com.cqupt.exception.BusinessException;
import com.cqupt.model.vo.ResultCodeEnum;
import com.cqupt.model.vo.ScoreVO;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XmlParserUtil {

    public static int getTotalScore(String xmlResult) {
        // 使用正则表达式提取total_score属性值
        String pattern = "total_score=\"([\\d.]+)\"";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(xmlResult);

        if (m.find()) {
            String totalScoreStr = m.group(1); // 获取匹配的分组（即total_score的值）
            double totalScore = Double.parseDouble(totalScoreStr);
            return (int) totalScore; // 转换为整数类型
        } else {
            // 如果找不到匹配项，则返回默认值
            return 0;
        }
    }

    public static ScoreVO getResult2(String xmlResult) {
        try {
            // 解析XML字符串
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new java.io.ByteArrayInputStream(xmlResult.getBytes("UTF-8")));

            // 获取根元素
            Element root = doc.getDocumentElement();

            // 获取read_chapter元素
            Element readChapter = (Element) root.getElementsByTagName("read_chapter").item(0);

            // 提取所需的分数
            String accuracyScore = readChapter.getAttribute("accuracy_score");
            String fluencyScore = readChapter.getAttribute("fluency_score");
            String integrityScore = readChapter.getAttribute("integrity_score");
            String totalScore = readChapter.getAttribute("total_score");

            ScoreVO scoreVO = new ScoreVO();
            scoreVO.setAccuracyScore(accuracyScore);
            scoreVO.setFluencyScore(fluencyScore);
            scoreVO.setIntegrityScore(integrityScore);
            scoreVO.setTotalScore(totalScore);
            return scoreVO;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static ScoreVO getResult3(String xmlResult) {
        try {
            // 解析XML字符串
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new java.io.ByteArrayInputStream(xmlResult.getBytes("UTF-8")));

            // 获取根元素
            Element root = doc.getDocumentElement();

            // 获取read_chapter元素
            Element readChapter = (Element) root.getElementsByTagName("read_chapter").item(0);

            // 提取所需的分数
            String accuracyScore = readChapter.getAttribute("accuracy_score");
            String fluencyScore = readChapter.getAttribute("fluency_score");
            String integrityScore = readChapter.getAttribute("integrity_score");
            String totalScore = readChapter.getAttribute("total_score");

            ScoreVO scoreVO = new ScoreVO();
            scoreVO.setAccuracyScore(accuracyScore);
            scoreVO.setFluencyScore(fluencyScore);
            scoreVO.setIntegrityScore(integrityScore);
            scoreVO.setTotalScore(totalScore);


            NodeList nodeList = doc.getElementsByTagName("word");
            ArrayList<String> wordScores = new ArrayList<>();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    wordScores.add(element.getAttribute("total_score"));
                }
            }

            scoreVO.setWordScores(wordScores);

            return scoreVO;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static ScoreVO getResult(String xmlResult) {
        // 定义输出文件路径
        String filePath = "output.xml";

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            // 将XML内容写入文件
            writer.write(xmlResult);
            writer.flush(); // 确保所有内容都写入文件
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        try {
            // 等待文件写入完成
            Thread.sleep(100);

            // 解析XML文件
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new File(filePath));

            // 获取read_chapter标签
            NodeList readChapterList = doc.getElementsByTagName("read_chapter");
            Element readChapter = (Element) readChapterList.item(0);
            // 提取read_chapter中的属性
            String accuracyScore = readChapter.getAttribute("accuracy_score");
            String fluencyScore = readChapter.getAttribute("fluency_score");
            String integrityScore = readChapter.getAttribute("integrity_score");
            String totalScore = readChapter.getAttribute("total_score");

            ScoreVO scoreVO = new ScoreVO();
            scoreVO.setAccuracyScore(accuracyScore);
            scoreVO.setFluencyScore(fluencyScore);
            scoreVO.setIntegrityScore(integrityScore);
            scoreVO.setTotalScore(totalScore);

            // 提取每个word标签中的total_score
            NodeList wordList = doc.getElementsByTagName("word");
            List<String> wordScores = new ArrayList<>();
            for (int i = 0; i < wordList.getLength(); i++) {
                Element word = (Element) wordList.item(i);
                String wordTotalScore = word.getAttribute("total_score");
                if (!StrUtil.isEmpty(wordTotalScore)) {
                    wordScores.add(wordTotalScore);
                }
            }
            scoreVO.setWordScores(wordScores);
            System.out.println(scoreVO); // 输出结果，供调试使用
            return scoreVO;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}